package com.example.personal.aiagent.xunfei.account.service;

import com.alibaba.fastjson.JSON;
import com.example.personal.aiagent.common.constant.ErrorCode;
import com.example.personal.aiagent.common.exception.CustomServiceException;
import com.example.personal.aiagent.user.mapper.UserMapper;
import com.example.personal.aiagent.xunfei.account.mapper.AccountMapper;
import com.example.personal.aiagent.xunfei.account.model.dto.AccountDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AccountServiceAbility implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void insertAccount(AccountDTO accountDTO) {
        if (userMapper.selectById(accountDTO.getUserId()) == null) {
            throw new CustomServiceException(ErrorCode.USER_NOT_EXIST);
        }
        AccountDTO preAccount = selectAccount(accountDTO.getUserId());
        if (preAccount != null) {
            throw new CustomServiceException(ErrorCode.ACCOUNT_EXISTS);
        }
        if (1 != accountMapper.insertAccount(AccountDTO.dTOToEntity(accountDTO))) {
            throw new CustomServiceException("insert account error :" + JSON.toJSONString(accountDTO));
        }
    }

    @Override
    public void updateAccount(AccountDTO accountDTO) {
        if (userMapper.selectById(accountDTO.getUserId()) == null) {
            throw new CustomServiceException(ErrorCode.USER_NOT_EXIST);
        }
        AccountDTO preAccount = selectAccount(accountDTO.getUserId());
        if (preAccount == null) {
            throw new CustomServiceException(ErrorCode.ACCOUNT_NOT_EXIST);
        }
        accountDTO.setId(preAccount.getId());
        if (1 != accountMapper.updateAccount(AccountDTO.dTOToEntity(accountDTO))) {
            throw new CustomServiceException("update account error :" + JSON.toJSONString(accountDTO));
        }
    }

    @Override
    public void deleteAccount(int userId) {
        if (userMapper.selectById(userId) == null) {
            throw new CustomServiceException(ErrorCode.USER_NOT_EXIST);
        }
        AccountDTO accountDTO = selectAccount(userId);
        if (accountDTO == null) {
            throw new CustomServiceException(ErrorCode.ACCOUNT_NOT_EXIST);
        }
        if (1 != accountMapper.deleteById(accountDTO.getId())) {
            throw new CustomServiceException("delete account error, user id " + userId + ", account id" + accountDTO
                .getId());
        }
    }

    @Override
    public AccountDTO selectAccount(int userId) {
        return AccountDTO.entityToDTO(accountMapper.selectByUserId(userId));
    }
}
